<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use  Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\User;

class Ranking extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'ranking';
    protected $guarded = [];
    protected $hidden = [
        'deleted_at'
    ];

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    public function user()
    {
        return $this->belongsTo(User::class, 'id');
    }

    /**
     * SELECT *,
     * ROW_NUMBER() OVER (ORDER BY solve_num DESC, update_time ASC) as user_rank
     * from ranking
     * ORDER BY solve_num DESC, update_time ASC;
     */
    public function scopeRankingBase($query)
    {
        $query->selectRaw('ROW_NUMBER() OVER (ORDER BY solve_num DESC, update_time ASC) as user_rank')
        ->orderBy('solve_num', 'DESC')
        ->orderBy('update_time', 'ASC');
    }

    /**
     * 集合的运用
     */
    public static function getUserRank($id)
    {
        $ranking = Ranking::select('id')
        ->RankingBase()->get();

        $ranking = $ranking->firstWhere('id', $id);

        return $ranking!=null ? $ranking->user_rank : null;
    }
}
